<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SquareHoleChecker - 零件孔位检测系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        danger: '#EF4444',
                        neutral: '#64748B',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .shadow-soft {
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            }
            .transition-custom {
                transition: all 0.3s ease;
            }
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen font-sans">
    <header class="bg-white shadow-md">
        <div class="container mx-auto px-4 py-6">
            <div class="flex flex-col md:flex-row justify-between items-center">
                <div class="flex items-center mb-4 md:mb-0">
                    <i class="fa fa-cogs text-primary text-3xl mr-3"></i>
                    <h1 class="text-2xl font-bold text-gray-800">SquareHoleChecker</h1>
                </div>
                <p class="text-neutral">零件孔位正方形检测系统</p>
            </div>
        </div>
    </header>

    <main class="container mx-auto px-4 py-8">
        <section class="max-w-5xl mx-auto">
            <!-- 上传区域 -->
            <div class="bg-white rounded-xl shadow-soft p-6 mb-8">
                <h2 class="text-xl font-semibold mb-4 text-gray-800">上传零件图片</h2>
                <div class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-primary transition-custom cursor-pointer" id="dropArea">
                    <i class="fa fa-cloud-upload text-5xl text-primary mb-4"></i>
                    <p class="mb-2 text-gray-600">拖放图片到此处，或点击选择文件</p>
                    <p class="text-sm text-gray-500">支持 JPG, PNG, WEBP 格式</p>
                    <input type="file" id="fileInput" class="hidden" accept="image/*">
                    <button id="uploadBtn" class="mt-4 bg-primary hover:bg-primary/90 text-white px-6 py-2 rounded-lg transition-custom">
                        <i class="fa fa-file-image-o mr-2"></i>选择图片
                    </button>
                </div>
            </div>

            <!-- 处理和结果展示区域 -->
            <div id="resultsArea" class="hidden">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-8 mb-8">
                    <!-- 原始图片 -->
                    <div class="bg-white rounded-xl shadow-soft p-6">
                        <h3 class="text-lg font-medium mb-3 text-gray-800">原始图片</h3>
                        <div class="aspect-video bg-gray-100 rounded-lg flex items-center justify-center overflow-hidden">
                            <img id="originalImage" src="" alt="原始零件图片" class="max-w-full max-h-full object-contain">
                        </div>
                    </div>

                    <!-- 处理后图片 -->
                    <div class="bg-white rounded-xl shadow-soft p-6">
                        <h3 class="text-lg font-medium mb-3 text-gray-800">处理后图片</h3>
                        <div class="aspect-video bg-gray-100 rounded-lg flex items-center justify-center overflow-hidden">
                            <img id="processedImage" src="" alt="处理后的零件图片" class="max-w-full max-h-full object-contain">
                        </div>
                    </div>
                </div>

                <!-- 检测结果 -->
                <div class="bg-white rounded-xl shadow-soft p-6">
                    <h3 class="text-lg font-medium mb-4 text-gray-800">检测结果</h3>
                    <div id="detectionResult" class="p-4 rounded-lg border">
                        <!-- 结果将在这里动态显示 -->
                    </div>

                    <div class="mt-6">
                        <h4 class="font-medium mb-2 text-gray-800">孔位坐标信息</h4>
                        <div class="overflow-x-auto">
                            <table class="min-w-full border-collapse">
                                <thead>
                                    <tr class="bg-gray-50">
                                        <th class="border border-gray-300 px-4 py-2 text-left">孔编号</th>
                                        <th class="border border-gray-300 px-4 py-2 text-left">X坐标</th>
                                        <th class="border border-gray-300 px-4 py-2 text-left">Y坐标</th>
                                    </tr>
                                </thead>
                                <tbody id="holesTableBody">
                                    <!-- 孔位数据将在这里动态显示 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 处理中状态 -->
            <div id="processingArea" class="hidden bg-white rounded-xl shadow-soft p-8 text-center">
                <div class="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary mb-4"></div>
                <h3 class="text-lg font-medium text-gray-800">正在处理图片...</h3>
                <p class="text-neutral mt-2">请稍候，系统正在分析零件孔位</p>
            </div>
        </section>
    </main>

    <footer class="bg-gray-800 text-white py-8 mt-12">
        <div class="container mx-auto px-4">
            <div class="text-center">
                <p class="mb-2">SquareHoleChecker - 零件孔位检测系统</p>
                <p class="text-sm text-gray-400">© 2023 版权所有</p>
            </div>
        </div>
    </footer>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const dropArea = document.getElementById('dropArea');
            const fileInput = document.getElementById('fileInput');
            const uploadBtn = document.getElementById('uploadBtn');
            const resultsArea = document.getElementById('resultsArea');
            const processingArea = document.getElementById('processingArea');
            const originalImage = document.getElementById('originalImage');
            const processedImage = document.getElementById('processedImage');
            const detectionResult = document.getElementById('detectionResult');
            const holesTableBody = document.getElementById('holesTableBody');

            // 点击上传按钮触发文件选择
            uploadBtn.addEventListener('click', () => {
                fileInput.click();
            });

            // 文件选择变化时处理
            fileInput.addEventListener('change', (e) => {
                if (e.target.files.length > 0) {
                    processFile(e.target.files[0]);
                }
            });

            // 拖放功能
            dropArea.addEventListener('dragover', (e) => {
                e.preventDefault();
                dropArea.classList.add('border-primary');
            });

            dropArea.addEventListener('dragleave', () => {
                dropArea.classList.remove('border-primary');
            });

            dropArea.addEventListener('drop', (e) => {
                e.preventDefault();
                dropArea.classList.remove('border-primary');
                if (e.dataTransfer.files.length > 0) {
                    processFile(e.dataTransfer.files[0]);
                }
            });

            // 点击拖放区域也触发文件选择
            dropArea.addEventListener('click', (e) => {
                if (e.target !== uploadBtn) {
                    fileInput.click();
                }
            });

            // 处理文件上传
            function processFile(file) {
                // 检查文件类型
                if (!file.type.match('image.*')) {
                    alert('请上传图片文件');
                    return;
                }

                // 显示原始图片
                const reader = new FileReader();
                reader.onload = (e) => {
                    originalImage.src = e.target.result;

                    // 显示处理中状态
                    resultsArea.classList.add('hidden');
                    processingArea.classList.remove('hidden');

                    // 模拟处理过程（实际项目中会调用后端API）
                    // 创建FormData对象，用于发送文件
                    const formData = new FormData();
                    formData.append('file', file); // 将用户上传的文件添加到表单

                    // 调用后端/upload接口
                    fetch('/upload', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('服务器响应错误');
                        }
                        return response.json();
                    })
                    .then(data => {
                        // 隐藏处理中状态，显示结果
                        processingArea.classList.add('hidden');
                        resultsArea.classList.remove('hidden');

                        // 显示处理后的图片
                        processedImage.src = `/processed/${data.processed_filename}`;

                        // 显示检测结果
                        if (data.hole_count !== 4) {
                            detectionResult.className = 'p-4 rounded-lg border border-danger bg-red-50';
                            detectionResult.innerHTML = `
                                <div class="flex items-start">
                                    <i class="fa fa-exclamation-circle text-danger text-xl mt-1 mr-3"></i>
                                    <div>
                                        <h4 class="font-medium text-danger mb-1">检测失败</h4>
                                        <p>检测到 ${data.hole_count} 个孔，不符合4个孔的要求。</p>
                                    </div>
                                </div>
                            `;
                        } else if (data.is_square) {
                            detectionResult.className = 'p-4 rounded-lg border border-secondary bg-green-50';
                            detectionResult.innerHTML = `
                                <div class="flex items-start">
                                    <i class="fa fa-check-circle text-secondary text-xl mt-1 mr-3"></i>
                                    <div>
                                        <h4 class="font-medium text-secondary mb-1">检测通过</h4>
                                        <p>零件上的4个孔中心构成一个正方形，符合要求。</p>
                                    </div>
                                </div>
                            `;
                        } else {
                            detectionResult.className = 'p-4 rounded-lg border border-danger bg-red-50';
                            detectionResult.innerHTML = `
                                <div class="flex items-start">
                                    <i class="fa fa-exclamation-circle text-danger text-xl mt-1 mr-3"></i>
                                    <div>
                                        <h4 class="font-medium text-danger mb-1">检测失败</h4>
                                        <p>检测到4个孔，但孔中心不构成正方形（误差超过10像素）。</p>
                                        <p class="text-sm mt-1">原因：${data.message}</p>
                                    </div>
                                </div>
                            `;
                        }

                        // 填充孔位表格
                        fillHolesTable(data.hole_centers);
                    })
                    .catch(error => {
                        console.error('检测过程出错：', error);
                        alert('检测失败，请重试！');
                        processingArea.classList.add('hidden');
                    });
                };
                reader.readAsDataURL(file);
            }

            // 模拟处理结果（实际项目中会替换为后端API调用）
            function simulateProcessing() {
                // 隐藏处理中状态，显示结果
                processingArea.classList.add('hidden');
                resultsArea.classList.remove('hidden');

                // 模拟处理后的图片（实际项目中是后端处理后的图片）
                processedImage.src = originalImage.src;

                // 模拟检测结果
                const isSquare = Math.random() > 0.3; // 70%概率为正方形
                const holeCount = 4; // 假设检测到4个孔

                // 显示检测结果
                if (holeCount !== 4) {
                    detectionResult.className = 'p-4 rounded-lg border border-danger bg-red-50';
                    detectionResult.innerHTML = `
                        <div class="flex items-start">
                            <i class="fa fa-exclamation-circle text-danger text-xl mt-1 mr-3"></i>
                            <div>
                                <h4 class="font-medium text-danger mb-1">检测失败</h4>
                                <p>检测到 ${holeCount} 个孔，不符合4个孔的要求。</p>
                            </div>
                        </div>
                    `;
                    holesTableBody.innerHTML = '';
                } else if (isSquare) {
                    detectionResult.className = 'p-4 rounded-lg border border-secondary bg-green-50';
                    detectionResult.innerHTML = `
                        <div class="flex items-start">
                            <i class="fa fa-check-circle text-secondary text-xl mt-1 mr-3"></i>
                            <div>
                                <h4 class="font-medium text-secondary mb-1">检测通过</h4>
                                <p>零件上的4个孔中心构成一个正方形，符合要求。</p>
                            </div>
                        </div>
                    `;
                    // 填充孔位数据
                    fillHolesTable([
                        {x: 120, y: 120},
                        {x: 320, y: 120},
                        {x: 320, y: 320},
                        {x: 120, y: 320}
                    ]);
                } else {
                    detectionResult.className = 'p-4 rounded-lg border border-danger bg-red-50';
                    detectionResult.innerHTML = `
                        <div class="flex items-start">
                            <i class="fa fa-exclamation-circle text-danger text-xl mt-1 mr-3"></i>
                            <div>
                                <h4 class="font-medium text-danger mb-1">检测失败</h4>
                                <p>检测到4个孔，但孔中心不构成正方形（误差超过10像素）。</p>
                            </div>
                        </div>
                    `;
                    // 填充孔位数据
                    fillHolesTable([
                        {x: 125, y: 120},
                        {x: 320, y: 130},
                        {x: 310, y: 325},
                        {x: 115, y: 315}
                    ]);
                }
            }

            // 填充孔位表格
            function fillHolesTable(holes) {
                holesTableBody.innerHTML = '';
                holes.forEach((hole, index) => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td class="border border-gray-300 px-4 py-2">${index + 1}</td>
                        <td class="border border-gray-300 px-4 py-2">${hole.x}</td>
                        <td class="border border-gray-300 px-4 py-2">${hole.y}</td>
                    `;
                    holesTableBody.appendChild(row);
                });
            }
        });
    </script>
</body>
</html>
